package com.zhe.zheblogmaster.handler.admin;

import com.zhe.zheblogmaster.config.BlogConstants;
import com.zhe.zheblogmaster.entity.AdminUser;
import com.zhe.zheblogmaster.service.*;
import com.zhe.zheblogmaster.util.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author WHAOU
 * @date 2021/9/2
 * @email whaou@qq.com
 */
@ResponseBody
@Controller
@RequestMapping("/admin")
public class AdminHandler {
    @Autowired
    private AdminUserService userService;
    @Autowired
    private BlogCategoryService categoryService;
    @Autowired
    private BlogService blogService;
    @Autowired
    private LinkService linkService;
    @Autowired
    private BlogCommentService commentService;


    /**
     * 获取数据观星页面数据
     *
     * @return 返回 博客分类数目 博客数目 友链数目 评论数目
     */
    @GetMapping("/overview")
    public ResultBody<Map<String, Integer>> getIndexInfo() {
        Map<String, Integer> param = new HashMap<>(5);
        Integer categoryCount = categoryService.getTotalCategories();
        param.put("categoryCount", categoryCount);
        Integer blogCount = blogService.getTotalBlogs();
        param.put("blogCount", blogCount);
        Integer linkCount = linkService.getTotalLinks();
        param.put("linkCount", linkCount);
        Integer commentCount = commentService.getTotalComments();
        param.put("commentCount", commentCount);
        return ResultBody.successWithData(param);
    }

    /**
     * 登录方法
     *
     * @param userName   用户名
     * @param password   密码（未加密）
     * @param verifyCode 验证码
     * @return 登录成功则将用户id和昵称存入session；否则返回错误提示
     */
    @PostMapping("/login")
    public ResultBody<String> doLogin(@RequestParam("userName") String userName,
                                      @RequestParam("password") String password,
                                      @RequestParam("verifyCode") String verifyCode,
                                      HttpServletResponse response, HttpSession session) {

        if (verifyCode == null || "".equals(verifyCode)) {
            return ResultBody.error("验证码不能为空");
        }
        if (userName == null || "".equals(userName)) {
            return ResultBody.error("用户名不能为空");
        }
        if (password == null || "".equals(password)) {
            return ResultBody.error("密码不能为空");
        }
        String captcha = String.valueOf(session.getAttribute(BlogConstants.VERIFY_CODE));
        if ("".equals(captcha) || !verifyCode.equals(captcha)) {
            return ResultBody.error("验证码错误");
        }
        AdminUser user = userService.login(userName, password);
        if (user != null) {
            session.setAttribute("loginUser", user.getNickName());
            session.setAttribute("loginUserId", user.getAdminUserId());
            Cookie nickName = new Cookie("nickName", user.getNickName());
            response.addCookie(nickName);
            return ResultBody.successWithoutData();
        } else {
            return ResultBody.error("用户名或密码错误！");
        }
    }

    @PostMapping("/update/name")
    public ResultBody<String> updateName(HttpServletRequest request, HttpServletResponse response,
                                         @RequestParam("loginUserName") String userName,
                                         @RequestParam("nickName") String nickName) {
        if (!StringUtils.hasLength(userName)) {
            return ResultBody.error("登录名称为空");
        }
        if (!StringUtils.hasLength(nickName)) {
            return ResultBody.error("昵称为空");
        }
        HttpSession session = request.getSession();
        Integer loginUserId = (Integer) session.getAttribute("loginUserId");
        int count = userService.updateName(loginUserId, userName, nickName);
        if (count > 0) {
            session.setAttribute("loginUser", nickName);
            return ResultBody.successWithoutData();
        } else {
            return ResultBody.error("修改失败");
        }
    }

    @PostMapping("/update/password")
    public ResultBody<String> updatePassword(HttpServletRequest request,
                                             @RequestParam("originalPassword") String originalPassword,
                                             @RequestParam("newPassword") String newPassword) {
        if (!StringUtils.hasLength(originalPassword)) {
            return ResultBody.error("原密码为空");
        }
        if (!StringUtils.hasLength(newPassword)) {
            return ResultBody.error("新密码为空");
        }
        Integer loginUserId = (Integer) request.getSession().getAttribute("loginUserId");
        int count = userService.updatePassword(loginUserId, originalPassword, newPassword);
        if (count > 0) {
            return ResultBody.successWithoutData();
        } else {
            return ResultBody.error("密码修改失败");
        }
    }

    @GetMapping("/logout")
    public ResultBody<String> logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
        return ResultBody.successWithoutData();
    }
}
